<script lang="ts" setup>
// vue
import { useRouter } from "vue-router";

// 组件
import { Search } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import ShareDialog from "@/views/associationAnalysis/components/ShareDialog.vue";

// 接口
import {
  fetchCanvasPage,
  fetchRename,
  fetchDestroy,
  fetchCanvas,
} from "@/api/associationAnalysis";

// Store
import { useCanvasStoreHook } from "@/stores/modules/canvas";

const router = useRouter();

const useCanvasStore = useCanvasStoreHook();

// tab标签组件
const activeName = ref("/kg-service/canvas/page");
const tabOption = [
  {
    label: "全部",
    name: "/kg-service/canvas/page",
  },
  {
    label: "个人文件",
    name: "/kg-service/canvas/create-by-me",
  },
  {
    label: "收到的分享",
    name: "/kg-service/canvas/shared-for-me",
  },
];

// 日期选择器组件
const time = ref("");

// 输入框组件
const name = ref("");

// list数据
const list = ref([]);
const fetchPage = async () => {
  let params = {
    name: name.value,
    startDate: time.value ? time.value[0] : "",
    endDate: time.value ? time.value[1] : "",
  };
  let url = activeName.value;
  const { data } = await fetchCanvasPage(url, params);
  list.value = data?.records || [];
};
fetchPage();

// 选中的下标
const selectId = ref(null);
const isEdit = ref(false);

// 单击item选中，赋值下标
const handleSelect = (id: string) => {
  if (selectId.value === id) return;
  selectId.value = id;
  isEdit.value = false;
};

// 选中时添加新的样式
const getIsSelectClass = (id: string) => {
  if (selectId.value === id) return "isSelect";
  return "";
};

// 重命名方法
const handleRename = () => {
  if (selectId.value === null) {
    ElMessage({
      message: "单击选中要重命名的文件",
      type: "warning",
    });
    return;
  }
  isEdit.value = true;
};

// 重命名保存接口
const handleRenameSave = async (id: string, name: string) => {
  if (name == "") {
    fetchPage();
    isEdit.value = false;
    selectId.value = null;
    return;
  }
  try {
    await fetchRename({ id, name });
    fetchPage();
    isEdit.value = false;
    selectId.value = null;
  } catch (error) {
    ElMessage.error(error);
  }
};

// 删除文件接口
const fetchDelete = async (id: string) => {
  try {
    await fetchDestroy(id);
    fetchPage();
    isEdit.value = false;
    selectId.value = null;
    ElMessage({
      type: "success",
      message: "删除成功",
    });
  } catch (error) {
    ElMessage.error(error);
  }
};

// 删除文件操作提示
const handleDelete = () => {
  if (selectId.value === null) {
    ElMessage({
      message: "单击选中要删除的文件",
      type: "warning",
    });
    return;
  }
  const id = selectId.value;
  const name = list.value.find((item) => item.id === id).name;
  ElMessageBox.confirm(`确定删除文件《${name}》?`, "确认删除", {
    confirmButtonText: "删除",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    fetchDelete(id);
  });
};

// 弹窗标识
const ShareDialogShow = ref(false);
// 分享
const handleShare = () => {
  if (selectId.value === null) {
    ElMessage({
      message: "单击选中要分享的文件",
      type: "warning",
    });
    return;
  }
  ShareDialogShow.value = true;
};

const canvasPath = "/associationAnalysis/canvas/index";
// 新增画布按钮操作
const handleCanvasAdd = () => {
  useCanvasStore.closeAllCanvas(); // 进入前先清除本地画布
  let uuid = `${Date.now()}`;
  useCanvasStore.pushCanvas({
    uuid,
    name: `临时文件${uuid}`,
    data: {
      nodes: [],
      edges: [],
    },
  });
  router.push(canvasPath);
};

// 画布双击事件
const handelDbClick = async (id) => {
  try {
    let { data } = await fetchCanvas(id);
    let dataJson = null;
    try {
      dataJson = JSON.parse(data.data);
    } catch (d) {
      dataJson = {};
    }
    useCanvasStore.closeAllCanvas(); // 进入前先清除本地画布

    useCanvasStore.pushCanvas({
      id: data.id,
      uuid: data.id,
      name: data.name,
      data: dataJson,
    });
    router.push(canvasPath);
  } catch (error) {
    ElMessage.error(error);
  }
};
</script>

<template>
  <div class="associationAnalysis">
    <el-card class="w-full h-full">
      <!--    top部分-->
      <div class="w-full relative">
        <el-tabs v-model="activeName" @tab-change="fetchPage">
          <!--tab标签页部分-->
          <el-tab-pane
            v-for="({ label, name }, index) in tabOption"
            :key="index"
            :label="label"
            :name="name"
          ></el-tab-pane>
        </el-tabs>
        <!--      筛选条件部分-->
        <div
          class="absolute right-0 top-0 flex items-center justify-end w-auto"
        >
          <el-date-picker
            v-model="time"
            class="mr-4"
            end-placeholder="结束日期"
            range-separator="至"
            start-placeholder="开始日期"
            style="width: 368px"
            type="daterange"
            value-format="YYYY-MM-DD"
          />
          <el-input
            v-model="name"
            class="mr-4"
            clearable
            placeholder="请输入要搜索的文件名"
            style="width: 267px"
          />
          <el-button @click="fetchPage">
            <el-icon class="mr-2">
              <Search />
            </el-icon>
            搜索文件
          </el-button>
          <el-button type="primary" @click="handleCanvasAdd">
            新增画布
          </el-button>
        </div>
      </div>

      <!--    list部分-->
      <div>
        <template v-if="!list.length">
          <el-empty description="暂无数据" />
        </template>
        <template v-else>
          <ul class="canvas-list">
            <li
              v-for="(item, index) in list"
              :key="index"
              :class="getIsSelectClass(item.id)"
              class="item"
              @click="handleSelect(item.id)"
              @dblclick="handelDbClick(item.id)"
            >
              <div class="left">
                <img :src="item.thumbnail" alt="" />
                <div class="mask">双击进入画布</div>
              </div>
              <div class="right">
                <div v-if="selectId == item.id && isEdit" class="title">
                  <el-input
                    v-model="item.name"
                    placeholder="请输入文件名"
                    @dblclick.stop
                    @keyup.enter="handleRenameSave(item.id, item.name)"
                    maxlength="25"
                  />
                  <el-button
                    link
                    type="primary"
                    @dblclick.stop
                    @click="handleRenameSave(item.id, item.name)"
                  >
                    保存
                  </el-button>
                </div>
                <div v-else class="title">
                  <i class="iconfont icon_share_fil text-[#FF9F4E] mr-2" />
                  {{ item.name }}
                </div>

                <div class="msg">
                  <span class="text-[#7F8A9B]">作者：</span>
                  <p class="text-[#222222]">{{ item.authorName }}</p>
                </div>
                <div class="msg">
                  <span class="text-[#7F8A9B]">修改时间：</span>
                  <p class="text-[#222222]">{{ item.updateTime }}</p>
                </div>
              </div>
            </li>
          </ul>
        </template>
      </div>

      <!--      操作栏部分-->
      <div class="operate">
        <el-button @click="handleRename">
          <i class="iconfont icon_rename_fill mr-2"></i>
          重命名
        </el-button>
        <el-button @click="handleDelete">
          <i class="iconfont icon_delete_fill mr-2"></i>
          删 除
        </el-button>
        <el-button @click="handleShare">
          <i class="iconfont icon_share_fil mr-2"></i>
          分 享
        </el-button>
      </div>
    </el-card>

    <!--    分享人员弹窗-->
    <ShareDialog
      v-if="ShareDialogShow"
      :id="selectId"
      v-model:visible="ShareDialogShow"
    ></ShareDialog>
  </div>
</template>
<style lang="scss" scoped>
.associationAnalysis {
  position: absolute;
  box-sizing: border-box;
  width: calc(100% - 48px);
  height: calc(100% - 48px);
}

.canvas-list {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  width: 100%;
  height: calc(100vh - 296px);
  margin-top: 9px;
  overflow: auto;

  .item {
    display: flex;
    width: calc(50% - 8px);
    height: 200px;
    margin-bottom: 16px;
    background: #fff;
    border: 1px solid #dcdde2;
    border-radius: 4px;
    transition: 0.3s;

    .left {
      position: relative;
      flex: 1;
      height: 100%;
      overflow: hidden;
      background: #f7f8fa;

      img {
        width: 100%;
        height: 100%;
      }

      .mask {
        position: absolute;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
        display: flex;
        align-items: center;
        justify-content: center;
        font-family: PingFangSC-Regular, "PingFang SC";
        font-size: 14px;
        font-weight: 400;
        line-height: 22px;
        color: rgb(255 255 255 / 0%);
        background: rgb(34 34 34 / 0%);
        transition: 0.3s;
      }
    }

    .right {
      box-sizing: border-box;
      width: 264px;
      padding: 16px;

      .title {
        display: flex;
        align-items: center;
        margin-bottom: 16px;
        font-family: PingFangSC-Medium, "PingFang SC";
        font-size: 16px;
        font-weight: 500;
        line-height: 24px;
        word-break: break-all;
      }

      .msg {
        display: flex;
        margin-bottom: 11px;
        font-family: PingFangSC-Regular, "PingFang SC";
        font-size: 14px;
        font-weight: 400;
        line-height: 22px;
      }
    }

    &:hover {
      box-shadow: 0 5px 21px 0 rgb(13 22 50 / 10%);

      .mask {
        color: rgb(255 255 255 / 100%);
        background: rgb(34 34 34 / 20%);
      }
    }
  }

  .isSelect {
    border: 1px solid #2b1dff;
    box-shadow: 0 5px 21px 0 rgb(13 22 50 / 10%);

    .mask {
      color: rgb(255 255 255 / 100%) !important;
      background: rgb(34 34 34 / 20%) !important;
    }
  }
}

.operate {
  position: absolute;
  bottom: 0;
  left: 0;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  width: 100%;
  height: 85px;
  padding-left: 21px;
  border-top: 1px solid rgb(13 22 50 / 10%);
}
</style>
